package com.qiangesoft.qrcode.utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.GlobalHistogramBinarizer;
import com.google.zxing.datamatrix.encoder.SymbolShapeHint;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 条码工具类
 *
 * @author qiangesoft
 * @date 2024-05-06
 */
public class QrcodeUtil {

    /**
     * 宽
     */
    private static final int WIDTH = 300;

    /**
     * 高
     */
    private static final int HEIGHT = 300;

    /**
     * 图片格式
     */
    private static final String FORMAT = "png";

    /**
     * 黑色
     */
    private static final int BLACK = 0xFF000000;

    /**
     * 白色
     */
    private static final int WHITE = 0xFFFFFFFF;

    /**
     * 默认编码
     */
    private static String CHARSET = "UTF-8";

    /**
     * 生成二维码
     *
     * @param content
     * @param outputStream
     */
    public static void generateQRCode(String content, OutputStream outputStream) {
        generateQRCode(content, WIDTH, HEIGHT, BLACK, WHITE, outputStream);
    }

    /**
     * 生成二维码
     *
     * @param content
     * @param width
     * @param height
     * @param outputStream
     */
    public static void generateQRCode(String content, int width, int height, OutputStream outputStream) {
        generateQRCode(content, width, height, BLACK, WHITE, outputStream);
    }

    /**
     * 生成二维码
     *
     * @param content
     * @param width
     * @param height
     * @param onColor
     * @param offColor
     * @param outputStream
     */
    public static void generateQRCode(String content, int width, int height, int onColor, int offColor, OutputStream outputStream) {
        // 自定义配置
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.MARGIN, 1);
        hints.put(EncodeHintType.DATA_MATRIX_SHAPE, SymbolShapeHint.FORCE_SQUARE);

        generate(content, BarcodeFormat.QR_CODE, width, height, hints, onColor, offColor, FORMAT, outputStream);
    }

    /**
     * 生成条形码
     *
     * @param content
     * @param outputStream
     */
    public static void generateCode128(String content, OutputStream outputStream) {
        generateCode128(content, WIDTH, HEIGHT, BLACK, WHITE, outputStream);
    }

    /**
     * 生成条形码
     *
     * @param content
     * @param outputStream
     */
    public static void generateCode128(String content, int width, int height, OutputStream outputStream) {
        generateCode128(content, width, height, BLACK, WHITE, outputStream);
    }

    /**
     * 生成条形码
     *
     * @param content
     * @param outputStream
     */
    public static void generateCode128(String content, int width, int height, int onColor, int offColor, OutputStream outputStream) {
        // 自定义配置
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.MARGIN, 1);
        hints.put(EncodeHintType.DATA_MATRIX_SHAPE, SymbolShapeHint.FORCE_SQUARE);

        generate(content, BarcodeFormat.CODE_128, width, height, hints, onColor, offColor, FORMAT, outputStream);
    }

    /**
     * 生成码
     *
     * @param content       内容
     * @param barcodeFormat 条码格式
     * @param width         宽
     * @param height        高
     * @param hints         参数
     * @param onColor       码颜色
     * @param offColor      底色
     * @param imageFormat   图片格式
     * @param outputStream  输出流
     */
    private static void generate(String content, BarcodeFormat barcodeFormat, int width, int height, Map<EncodeHintType, Object> hints, int onColor, int offColor, String imageFormat, OutputStream outputStream) {
        try {
            // 生成二维码
            MultiFormatWriter writer = new MultiFormatWriter();
            BitMatrix matrix = writer.encode(content, barcodeFormat, width, height, hints);

            // 写入流中
            MatrixToImageConfig matrixToImageConfig = new MatrixToImageConfig(onColor, offColor);
            MatrixToImageWriter.writeToStream(matrix, imageFormat, outputStream, matrixToImageConfig);
        } catch (Exception e) {
            throw new RuntimeException("二维码生成异常");
        }
    }

    /**
     * 解码
     *
     * @param inputStream
     */
    public static void decode(InputStream inputStream) {
        // 自定义配置
        Map<DecodeHintType, String> hints = new HashMap<>();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);

        try {
            // 读图片
            BufferedImage image = ImageIO.read(inputStream);
            LuminanceSource source = new BufferedImageLuminanceSource(image);

            // 解析
            BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
            Result res = new MultiFormatReader().decode(bitmap, hints);

            System.out.println(res.getText());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
        generateQRCode("aaaaaaaaaa", new FileOutputStream("C:\\Users\\16\\Desktop\\qrcode.png"));
        generateCode128("aaaaaaaaaa", new FileOutputStream("C:\\Users\\16\\Desktop\\code128.png"));
        decode(new FileInputStream("C:\\Users\\16\\Desktop\\qrcode.png"));
    }
}